﻿// document.getElementById('nav').innerHTML = template('navs', navinfo4);
$('.indexl43').addClass('active');

var qiniu1 = QiniuInit();
var info = getUrlId().split('=');
var submitObj = {};
var b;

GetDictionarys('CITY_TRAFFIC, DOWNTOWN_TRAFFIC', function (data) {
  var arr = {};
  // console.log(JSON.stringify(data));
  var obj = {};
  var list = data.ApiParamObj;
  var i = 0;
  var l = list.length;

  for (; i < l; i++) {
    if (!obj[list[i].Key]) {
      obj[list[i].Key] = [];
      arr[list[i].Key] = list[i].Logogram;
    }
    obj[list[i].Key].push(list[i]);
  }
  // console.log(obj)
  load(obj, arr);
});
/*getProjectInfo();
 function getProjectInfo() {
 $.ajax({
 url: '/api/CommonApi?API=GetProject',
 type: 'get',
 data: {
 ProjectID: info[2]
 },
 dataType: 'json',
 success: function (data) {
 if (data.Success) {
 // console.log(data)
 var obj = data.ApiParamObj[0];
 var date = new Date(obj.StartDate).pattern('yyyy年MM月dd日');
 var t = obj.ProjectBrand + '-' + obj.ProjectType + '-' + date + '-' + obj.ProjectStage;
 $('#projectInfo h1').html(t);
 $('#projectInfo h3').html(data);
 }
 }
 });
 }*/
getLimit();
function getLimit() {
  $.ajax({
    cache: false,
    async: false,
    url: '/api/CommonApi?API=GetTeacherScheduleCostAstrict',
    type: 'get',
    data: {
      TeacherScheduleID: info[1]
    },
    dataType: 'json',
    success: function (data) {
      // console.log(data)
      if (data.Success) {
        // console.log(data)
        var obj = data.ApiParamObj[0];
        // console.log(obj)
        var date = new Date(obj.StartTime).pattern('yyyy年MM月dd日');
        var t = obj.ProjectBrand + '-' + obj.ProjectType + '-' + date + '-' + obj.ProjectStage;
        $('#projectInfo h1').html(t);
        $('#projectInfo h3').html(data);

        // 城市间
        $('#CityTrafficCost .limit').html(obj.CityTrafficCost);
        // 城市内
        $('#DowntownTrafficCost .limit').html(obj.DowntownTrafficCost);
        // 住宿
        $('#AccommodationCost .limit').html(obj.AccommodationCost);
        // 包干
        $('#LivingCost .limit').html(obj.LivingCost);
        // 其他
        $('#OtherCost .limit').html(obj.OtherCost);
      }
    }
  });
}

function load(o, arr) {
  // console.log(o)
  b = new Vue({
    el: '#lists',
    data: {
      form1: {
        cName: '',
        cost: 0,
        info: ''
      },
      form2: {
        cName: '',
        cost: 0,
        info: ''
      },
      select1: o['CITY_TRAFFIC'],
      select2: o['DOWNTOWN_TRAFFIC'],
      allList1: [],
      allCost1: 0,
      allList2: [],
      allCost2: 0,
      other: {
        live1: 0,
        live2: '',
        lump1: 0,
        lump2: '',
        project1: 0,
        project2: ''
      }
    },
    methods: {
      change1: function () {
        var limit1 = parseInt($('#limit1').html(), 10);
        cost1(b);
        b.allCost1 = parseInt(b.allCost1, 10) + parseInt(b.form1.cost, 10);
        if (isNaN(b.allCost1)) {
          b.allCost1 = 0;
        }
        // console.log(b.form1.cost, b.allCost1)
        // if (b.allCost1 > limit1) {
        //   b.$set('form1.cost', limit1);
        //   b.$set('allCost1', limit1);
        //   alert('城市间交通费用金额不能超过' + limit1 + '元');
        // }
      },
      del1: function ($index) {
        b.allList1.splice($index, 1);
        cost1(b);
        // checkSave(b);
      },
      add1: function () {
        var v1 = b.form1.cName;
        var v2 = b.form1.cost;
        var v3 = b.form1.info;
        var limit1 = parseInt($('#limit1').html(), 10);

        var validator = new Validator();
        validator.add(v1, [{
          strategy: 'isNonEmpty',
          errorMsg: '城市间交通费用名称不能为空'
        }]);

        validator.add(v2, [{
          strategy: 'isNonEmpty',
          errorMsg: '城市间交通费用金额不能为空'
        }]);

        validator.add(parseInt(v2, 10), [{
          strategy: 'isRMB',
          errorMsg: '城市间交通费用金额必须为数字'
        }]);

        if (limit1 > 0) {
          validator.add({
            // value1: parseInt(v2, 10) + b.allCost1,
            value1: b.allCost1,
            value2: limit1
          }, [{
            strategy: 'compareValue',
            errorMsg: '城市间交通费用金额不能超过' + limit1 + '元'
          }]);
        }


        var errmsg = validator.start();
        if (errmsg) {
          alert(errmsg);
          return false;
        }

        // console.log(v1, v2);
        b.allList1.push({
          selected: v1,
          cost: v2,
          info: v3
        });

        cost1(b);

        b.form1 = {
          cName: '',
          cost: '',
          info: ''
        };
        // checkSave(b);
      },
      change2: function () {
        var limit2 = parseInt($('#limit2').html(), 10);
        cost2(b);
        b.allCost2 = parseInt(b.allCost2, 10) + parseInt(b.form2.cost, 10);
        if (isNaN(b.allCost2)) {
          b.allCost = 0;
        }
        // if (b.allCost2 > limit2) {
        //   b.$set('form2.cost', limit2);
        //   b.$set('allCost2', limit2);
        //   alert('城市间交通费用金额不能超过' + limit2 + '元');
        // }
      },
      del2: function ($index) {
        b.allList2.splice($index, 1);
        cost2(b);
        // checkSave(b);
      },
      add2: function () {
        var v1 = b.form2.cName;
        var v2 = b.form2.cost;
        var v3 = b.form2.info;
        var limit2 = parseInt($('#limit2').html(), 10);

        var validator = new Validator();
        validator.add(v1, [{
          strategy: 'isNonEmpty',
          errorMsg: '市内交通费用名称不能为空'
        }]);

        validator.add(v2, [{
          strategy: 'isNonEmpty',
          errorMsg: '市内交通费用金额不能为空'
        }]);

        validator.add(parseInt(v2, 10), [{
          strategy: 'isRMB',
          errorMsg: '市内交通费用金额必须为数字'
        }]);

        if (limit2 > 0) {
          validator.add({
            // value1: parseInt(v2, 10) + b.allCost2,
            value1: b.allCost2,
            value2: limit2
          }, [{
            strategy: 'compareValue',
            errorMsg: '市内交通费用金额不能超过' + limit2 + '元'
          }]);
        }

        var errmsg = validator.start();
        if (errmsg) {
          alert(errmsg);
          return false;
        }


        b.allList2.push({
          selected: v1,
          cost: v2,
          info: v3
        });

        cost2(b);

        b.form2 = {
          cName: '',
          cost: '',
          info: ''
        };
        // checkSave(b);
      }
    }
  });


  function cost1(b) {
    var i = 0;
    var l = b.allList1.length;
    b.allCost1 = 0;
    for (; i < l; i++) {
      b.allCost1 += parseInt(b.allList1[i].cost, 10);
    }
  }

  function cost2(b) {
    var i = 0;
    var l = b.allList2.length;
    b.allCost2 = 0;
    for (; i < l; i++) {
      b.allCost2 += parseInt(b.allList2[i].cost, 10);
    }
  }

  $('#save').on('click', function () {
    var allList1 = [];
    var allList2 = [];
    // console.log(info[1])
    // console.log(b.allList1)
    // console.log(b.allList2)
    // console.log(b.other)
    // console.log($('form')[0].file.value)
    var v1 = b.other.live1;
    var v2 = b.other.lump1;
    var v3 = b.other.project1;
    var v4 = $('#pickfiles').val();
    var l3 = $('#limit3').html();
    var l4 = $('#limit4').html();
    var l5 = $('#limit5').html();

    var validator = new Validator();


    var f1 = $('#f1 :selected').val();
    var f2 = $('#f2').val();
    var f3 = $('#f3').val();
    f1 = typeof(f1) === 'undefined' ? '' : f1;
    // if (!b.allList1.length) {
    //   // console.log(f1)
    //   check1();
    // } else {
    if (f1 || f2 || f3) {
      check1();
    }

    // }

    function check1() {

      var limit1 = parseInt($('#limit1').html(), 10);
      validator.add(f1, [{
        strategy: 'isNonEmpty',
        errorMsg: '城市间交通费用交通工具不能为空'
      }]);

      validator.add(f2, [{
        strategy: 'isNonEmpty',
        errorMsg: '城市间交通费用金额不能为空'
      }]);

      validator.add(parseInt(f2, 10), [{
        strategy: 'isRMB',
        errorMsg: '城市间交通费用金额必须为数字'
      }]);

      if (limit1 > 0) {
        validator.add({
          // value1: parseInt(f2, 10) + b.allCost1,
          value1: b.allCost1,
          value2: limit1
        }, [{
          strategy: 'compareValue',
          errorMsg: '城市间交通费用金额不能超过' + limit1 + '元'
        }]);
      }

      validator.add(f3, [{
        strategy: 'isNonEmpty',
        errorMsg: '城市间交通费用说明不能为空'
      }]);
    }

    // console.log(b.allList1);

    // if (!b.allList2.length) {
    var f4 = $('#f4 :selected').val();
    var f5 = $('#f5').val();
    var f6 = $('#f6').val();
    f4 = typeof(f4) === 'undefined' ? '' : f4;
    // console.log(f1)
    if (f4 || f5 || f6) {
      check2();
    }
    // }

    function check2() {
      var limit2 = parseInt($('#limit2').html(), 10);
      validator.add(f4, [{
        strategy: 'isNonEmpty',
        errorMsg: '市内交通费用交通工具不能为空'
      }]);

      validator.add(f5, [{
        strategy: 'isNonEmpty',
        errorMsg: '市内交通费用金额不能为空'
      }]);

      validator.add(parseInt(f5, 10), [{
        strategy: 'isRMB',
        errorMsg: '市内交通费用金额必须为数字'
      }]);

      if (limit2 > 0) {
        validator.add({
          // value1: parseInt(f5, 10) + b.allCost2,
          value1: b.allCost2,
          value2: limit2
        }, [{
          strategy: 'compareValue',
          errorMsg: '市内交通费用金额不能超过' + limit2 + '元'
        }]);
      }

      validator.add(f6, [{
        strategy: 'isNonEmpty',
        errorMsg: '市内交通费用说明不能为空'
      }]);
    }

    validator.add(v1, [{
      strategy: 'isNonEmpty',
      errorMsg: '住宿费用不能为空'
    }]);

    validator.add(parseInt(v1, 10), [{
      strategy: 'isRMB',
      errorMsg: '住宿费用必须为数字'
    }]);

    if (l3 > 0) {
      validator.add({
        value1: parseInt(v1, 10),
        value2: parseInt(l3, 10)
      }, [{
        strategy: 'compareValue',
        errorMsg: '住宿费用不能超过' + l3 + '元'
      }]);
    }


    validator.add(v2, [{
      strategy: 'isNonEmpty',
      errorMsg: '包干费用不能为空'
    }]);

    validator.add(parseInt(v2, 10), [{
      strategy: 'isRMB',
      errorMsg: '包干费用必须为数字'
    }]);

    if (l4 > 0) {
      validator.add({
        value1: parseInt(v2, 10),
        value2: parseInt(l4, 10)
      }, [{
        strategy: 'compareValue',
        errorMsg: '住宿费用不能超过' + l4 + '元'
      }]);
    }

    validator.add(v3, [{
      strategy: 'isNonEmpty',
      errorMsg: '项目费用不能为空'
    }]);

    validator.add(parseInt(v3, 10), [{
      strategy: 'isRMB',
      errorMsg: '项目费用必须为数字'
    }]);

    if (l5 > 0) {
      validator.add({
        value1: parseInt(v3, 10),
        value2: parseInt(l5, 10)
      }, [{
        strategy: 'compareValue',
        errorMsg: '住宿费用不能超过' + l5 + '元'
      }]);
    }

    validator.add(v4, [{
      strategy: 'isNonEmpty',
      errorMsg: '发票上传不能为空'
    }]);

    var errmsg = validator.start();
    if (errmsg) {
      alert(errmsg);
      return false;
    }

    var t1 = [];
    var t2 = [];
    var m1 = [];
    var m2 = [];
    var e1 = [];
    var e2 = [];
    var i = 0;
    var o = [];
    var l;

    if (!b.allList1.length) {
      allList1[0] = {
        selected: f1,
        cost: parseInt(f2, 10),
        info: f3
      };
      o = allList1;
    } else {
      if (f1 && f2 && f3) {
        allList1[0] = {
          selected: f1,
          cost: parseInt(f2, 10),
          info: f3
        };
        o = b.allList1;
        o.unshift(allList1[0]);
        // console.log(o);
      } else {
        o = b.allList1;
      }

    }

    l = o.length;
    for (; i < l; i++) {
      // console.log(o[i])
      m1.push(o[i].cost);
      t1.push('城市间交通费用-' + o[i].selected);
      if (o[i].info) {
        e1.push(o[i].selected + '说明-' + o[i].info);
      }

    }


    t1 = t1.join('P$=');
    m1 = m1.join('P$=');
    e1 = e1.join('P$=');

    // console.log(t1);
    // console.log(m1);
    // console.log(e1);
    // console.log(f4)
    o = [];
    if (!b.allList2.length) {
      allList2[0] = {
        selected: f4,
        cost: parseInt(f5, 10),
        info: f6
      };
      o = allList2;
    } else {
      if (f4 && f5 && f6) {
        allList2[0] = {
          selected: f4,
          cost: parseInt(f5, 10),
          info: f6
        };
        o = b.allList2;
        o.unshift(allList2[0]);
        // o.push(allList2[0]);
        // o.concat(b.allList2)
      } else {
        o = b.allList2;
      }

    }

    i = 0;
    l = o.length;
    for (; i < l; i++) {
      m2.push(o[i].cost);
      t2.push('市内交通费用-' + o[i].selected);
      if (o[i].info) {
        e2.push(o[i].selected + '说明-' + o[i].info);
      }
    }

    t2 = t2.join('P$=');
    m2 = m2.join('P$=');
    e2 = e2.join('P$=');

    o = b.other;
    var t3 = '住宿P$=包干P$=项目';
    var m3 = o.live1 + 'P$=' + o.lump1 + 'P$=' + o.project1;
    var e3 = [];
    if (o.live2) {
      e3.push('住宿说明-' + o.live2);
    }
    if (o.lump2) {
      e3.push('包干说明-' + o.lump2);
    }
    if (o.project2) {
      e3.push('项目说明-' + o.project2);
    }
    e3 = e3.join('P$=');

    var t = [t1, t2, t3].join('P$=');
    var m = [m1, m2, m3].join('P$=');
    i = 0;
    var obj = [e1, e2, e3];
    for (; i < obj.length; i++) {
      if (!obj[i]) {
        obj.splice(i, 1);
        i = i - 1;
      }
    }
    var e = obj.join('P$=');
    // console.log(obj)
    // var e = [e1, e2, e3].join('P$=');

    /*console.log(JSON.stringify({
     ProjectID: info[2],
     TeacherScheduleID: info[1],
     ApplyDate: info[0],
     CostType: t,
     CostMoney: m,
     CostExplain: e,
     InvoiceURL: $('form')[0].file.value
     }));*/

    submitObj = {
      ProjectID: info[2],
      TeacherScheduleID: info[1],
      ApplyDate: info[0],
      CostType: t,
      CostMoney: m,
      CostExplain: e,
      InvoiceURL: ''
    };
    // console.log(submitObj)

    loading.show();
    qiniu1.start();
    /*$.ajax({
     url: '/api/CommonApi?API=SetTeacherApply',
     type: 'get',
     data: submitObj,
     dataType: 'json',
     success: function (data) {
     if (data.Success) {
     console.log('add success');
     b.form1 = {
     cName: '',
     cost: '',
     info: ''
     };
     b.form2 = {
     cName: '',
     cost: '',
     info: ''
     };
     b.allList1 = [];
     b.allList2 = [];
     b.other = {
     live1: '',
     live2: '',
     lump1: '',
     lump2: '',
     project1: '',
     project2: ''
     };
     $('form')[0].file.value = '';
     $('#alert').modal('show');
     // window.location.href = '/Teacher/Project/indexl4';
     }
     }
     });*/

  });

  $('#alert').on('click', '#return', function () {
    window.location.href = '/Teacher/Project/indexl4';
  });
}

function allSubmit() {
  $.ajax({
    url: '/api/CommonApi?API=SetTeacherApply',
    type: 'get',
    data: submitObj,
    dataType: 'json',
    success: function (data) {
      if (data.Success) {
        console.log('add success');
        b.form1 = {
          cName: '',
          cost: '',
          info: ''
        };
        b.form2 = {
          cName: '',
          cost: '',
          info: ''
        };
        b.allList1 = [];
        b.allList2 = [];
        b.other = {
          live1: '',
          live2: '',
          lump1: '',
          lump2: '',
          project1: '',
          project2: ''
        };
        // $('form')[0].file.value = '';
        $('#pickfiles').html('');
        loading.hide();
        $('#alert').modal('show');
        // window.location.href = '/Teacher/Project/indexl4';
      }
    }
  });
}

function checkSave(b) {
  // console.log(b.allList1, b.allList2)
  if (b.allList1.length && b.allList2.length) {
    $('#save').removeAttr('disabled');
  } else {
    $('#save').attr('disabled', 'disabled');
  }
}

function QiniuInit(o) {
  var obj2 = Qiniu.uploader({
    runtimes: 'html5,flash,html4',
    browse_button: 'pickfiles',
    container: 'uploadContainer',
    drop_element: 'uploadContainer',
    max_file_size: '1000mb',
    flash_swf_url: '/Content/qiniu/plupload-2.1.8/js/Moxie.swf',
    dragdrop: false,
    chunk_size: '100mb',
    // multi_selection: !(mOxie.Env.OS.toLowerCase() === "ios"),
    uptoken_url: '/QINIU/GetUploadToken',
    domain: $('#domain').val(),
    get_new_uptoken: false,
    unique_names: true,
    auto_start: false,
    multi_selection: false,
    log_level: 5,
    init: {
      'FilesAdded': function (up, files) {
        // var fileNames = $('#fileName');
        var allFiles = [];
        // fileNames.html('');
        // console.log(up, files)
        var flength = up.files.length - files.length;
        for (var i = 0; i < flength; i++) {
          up.removeFile(up.files[0]);
        }

        plupload.each(up.files, function (file) {
          var tfile = file.name.substring(file.name.lastIndexOf('.'));

          if ('.jpg.png'.indexOf(tfile) == -1) {
            alert('选择文件格式不对，只能上传 ' + fileType[index] + ' 格式的文件，请重新选择！');
            return false;
          }
          allFiles.push(file.name);
        });
        $('#pickfiles').val(allFiles.join(', '));
        // console.log(allFiles)
        // qiniu1.start();

      },
      'BeforeUpload': function (up, file) {

      },
      'UploadProgress': function (up, file) {

      },
      'UploadComplete': function () {

      },
      'FileUploaded': function (up, file, info) {
        // debugger;
        // console.log(info)
        // info = JSON.parse(info);
        var url = $('#FileURL');
        // url.val(url.val() + ',' + $('#domain').val() + info.key);
        // alert('OK');
        // 上传成功后
        // 获取上传成功后的文件的Url
        var domain = up.getOption('domain');
        var res = JSON.parse(info);
        var sourceLink = domain + res.key;
        url.val(sourceLink);
        // console.log(sourceLink)
        submitObj.InvoiceURL = sourceLink;
        allSubmit();
      },
      'Error': function (up, err, errTip) {
      }
    }
  });
  return obj2;
}